package ex.hql.config;



import springfox.documentation.service.*;
import springfox.documentation.spi.service.contexts.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean//注册一个Docket对象，这个对象是Swagger规定的
    public Docket docket(){
        return  new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfo("Api Documentation",//title
                                "wry接口的文档",//描述
                                "1.0",//版本号
                                null,
                                new Contact("hql","http://localhost:8081/doc.html","1375041853@qq.com"),//与谁关联，我理解是作者信息
                                "Apache 2.0",//开源版本号
                                null,
                                new ArrayList<>()))
                .select()
                .apis(RequestHandlerSelectors.basePackage("ex.hql.controller"))
                .paths(PathSelectors.any())
                .build()
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes());
    }

    private List<ApiKey> securitySchemes(){
        List<ApiKey> apiKeyList=new ArrayList<>();
        ApiKey apiKey=new ApiKey("Authorization","Authorization","Header");
        apiKeyList.add(apiKey);
        return apiKeyList;

    }

    private List<SecurityContext> securityContexts(){
        //设置需要登录认证的路径
        List<SecurityContext> contexts=new ArrayList<>();
        contexts.add(getContextBypath("/hello/.*"));
        return contexts;

    }

    private SecurityContext getContextBypath(String path) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(path))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> securityReferences=new ArrayList<>();
        AuthorizationScope authorizationScope=new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] authorizationScopes=new AuthorizationScope[1];
        authorizationScopes[0]=authorizationScope;
        securityReferences.add(new SecurityReference("Authorization",authorizationScopes));
        return securityReferences;
    }

}
